﻿using System;
using System.Collections.Specialized;

namespace MetroNextTools.NData
{
    internal class WeakCollectionChangedListener
    {
        #region Fields

        private WeakReference _weakListener;
        private INotifyCollectionChanged _source;

        #endregion
        private WeakCollectionChangedListener(INotifyCollectionChanged source, ICollectionChangedListener listener)
        {
            this._source = source;
            this._source.CollectionChanged += SourceCollectionChanged;
            this._weakListener = new WeakReference(listener);
        }

        internal static WeakCollectionChangedListener CreateIfNecessary(object source, ICollectionChangedListener listener)
        {
            if (source is INotifyCollectionChanged)
            {
                return new WeakCollectionChangedListener(source as INotifyCollectionChanged, listener);
            }
            return null;
        }

        void SourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (_weakListener == null)
            {
                return;
            }
            ICollectionChangedListener collectionChangedListener = this._weakListener.Target as ICollectionChangedListener;
            if (collectionChangedListener != null)
            {
                collectionChangedListener.OnCollectionChanged(sender, e);
                return;
            }
            this.Disconnect();
        }

        internal void Disconnect()
        {
            if (this._source == null)
            {
                return;
            }
            this._source.CollectionChanged -= SourceCollectionChanged;
            this._source = null;
            this._weakListener = null;
        }
    }
}
